package com.maslyk.invitation;

import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.myfaces.webapp.StartupServletContextListener;

import com.maslyk.configuration.ConfigurationManager;
import com.maslyk.configuration.DataCache;
import com.maslyk.invitation.entitybean.Text;
import com.maslyk.invitation.enums.LocalNames;
import com.maslyk.invitation.service.PersistenceService;
import com.maslyk.job.AutomaticJob;

/**
 * @author kris
 */
public class StartupListener extends StartupServletContextListener implements ServletContextListener
{
    public void contextDestroyed(ServletContextEvent event)
    {
    	super.contextDestroyed(event);
    	
    	PersistenceService.getInstance().getEntityManager().close();
        DataCache.getInstance().clearCache();
        stopJob();
        
        System.out.println("Invitation zatrzymana!");
    }

    public void contextInitialized(ServletContextEvent event)
    {
        super.contextInitialized(event);
    	initializeAppData();
    	initializeJob();
        System.out.println("Invitation uruchomiona!");
    }

    public void initializeAppData()
    {
        handleTextList();
    }

    private void handleTextList()
    {
        List<Text> texts = PersistenceService.getInstance().getTextList();
        DataCache.getInstance().getCache().put(LocalNames.TEXT_LIST, texts);
    }
    
    private void initializeJob()
    {
        int minutes = ConfigurationManager.getInstance().getEMAIL_PROCESSING_PERIOD();
        AutomaticJob.initializeJob(minutes * 60L * 1000L);
    }
    
    private void stopJob()
    {
    	AutomaticJob.stop();
    }
    
}
